import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

// 演示 HttpServletResponse 的方法
@WebServlet("/showRequest")
public class ShowRequestServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 调用 HttpServletRequest 的核心方法
        // 然后把结果组织到一个 html 中, 作为响应的 body
        StringBuilder sb = new StringBuilder();
        sb.append("<h3>首行部分</h3>");
        sb.append(req.getProtocol());
        sb.append("<br>"); // 换行
        sb.append(req.getMethod());
        sb.append("<br>");
        sb.append(req.getRequestURI());
        sb.append("<br>");
        sb.append(req.getContextPath());
        sb.append("<br>");
        sb.append(req.getQueryString());
        sb.append("<br>");
        sb.append("<h3>header 部分</h3>");
        // 枚举类
        Enumeration<String> headerNames = req.getHeaderNames();
        // 拿到 header 里所有的 key, 然后循环获取对应的 value
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = req.getHeader(headerName);
            sb.append(headerName + ": " + headerValue + "<br>");
        }

        resp.setContentType("text/html; charset=utf8");
        resp.getWriter().write(sb.toString());
    }
}
